package com.atguigu.tingshu.album.consumer;

import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/***
 * 监听redis数据一致性的消息：专辑修改/删除
 */
@Component
@Log4j2
public class RedisMessageConsumer {

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 专辑发生删除 / 修改操作时，删除其在Redis中对应的数据
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(queues = "album_and_search_queue_redis")
    public void redisMessageConsumerListener(Message message, Channel channel){
        // 从message中获取专辑id
        Long albumId = Long.valueOf(new String(message.getBody()));
        // 获取messageProperties
        MessageProperties messageProperties = message.getMessageProperties();
        // 获取消息编号
        long deliveryTag = messageProperties.getDeliveryTag();
        try{
            // 删除Redis中专辑的数据
            redisTemplate.delete("getAlbumInfo:" + Arrays.asList(albumId).toString());
            // 删除Redis中专辑的统计数据
            redisTemplate.delete("getAlbumStatMap:" + Arrays.asList(albumId).toString());
            // 手动确认消息
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            // 判断是否是重试的消息
            if (messageProperties.isRedelivered()){
                // 是重试的,将错误信息记录到日志后拒绝消息
                log.error("Redis数据删除失败，失败原因：" +
                        e.getMessage() + "。专辑：id = " + albumId );
                // 拒绝消息
                channel.basicReject(deliveryTag,false);
            }else {
                // 不是重试消息，放回队列再消费一次
                channel.basicReject(deliveryTag,true);
            }
        }
    }
}
